package com.property.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.property.biz.CommunityBiz;
import com.property.biz.ComplaintBiz;
import com.property.biz.HomemakeBiz;
import com.property.biz.InformTargetBiz;
import com.property.biz.ManagementBiz;
import com.property.biz.OwnerBiz;
import com.property.biz.ProvCityDistBiz;
import com.property.biz.UserBiz;
import com.property.entity.Community;
import com.property.entity.Complaint;
import com.property.entity.ComplaintDispose;
import com.property.entity.Homemake;
import com.property.entity.InformTarget;
import com.property.entity.Management;
import com.property.entity.Owner;
import com.property.entity.ProvCityDist;
import com.property.entity.User;

@Controller
@RequestMapping("/owner")
public class OwnerController {
	@Autowired
	private UserBiz userBiz;
	@Autowired
	private OwnerBiz ownerBiz;
	@Autowired
	private HomemakeBiz homemakeBiz;

	@Autowired
	private ComplaintBiz complaintBiz;
	@Autowired
	private CommunityBiz communityBiz;
	@Autowired
	private ManagementBiz managementBiz;

	@Autowired
	private InformTargetBiz informTargetBiz;

	@Autowired
	private ProvCityDistBiz provCityDistBiz;

	@RequestMapping("/index")
	public String index() {
		return "owner/index";
	}

	@RequestMapping("/compilewrite")
	public String compilewritea(Model model, HttpSession session,
			String userName, String password) {

		return "owner/compilewrite";
	}

	@RequestMapping(value = "/docompilewrite", method = RequestMethod.POST)
	public String compilewrite(Model model, HttpSession session, String name,
			String password, String email) {
		User user = (User) session.getAttribute("user");
		user.setUserName(name);
		user.setEmail(email);
		user.setPassWord(password);
		if (user.getUserName() == name) {
			userBiz.updateUser(user);
		} else {
			return "owner/compilewrite";
		}
		return "owner/index";
	}

	@RequestMapping(value = "/homemakeList")
	public String dispose2(Model model, HttpSession session, String name1,
			Integer id, Integer page) {
		User user = (User) session.getAttribute("user");
		page = page == null ? 1 : page;
		id = id == null ? 0 : id;
		int pageSize = 5;
		int startIndex = (page - 1) * pageSize;
		int rows = homemakeBiz.comCount(name1, id);
		int pageCount = (int) Math.ceil((double) rows / pageSize);
		List<Homemake> homemakes = homemakeBiz.getHomemake(id, name1,
				startIndex, pageSize);
		model.addAttribute("homemakes", homemakes);
		model.addAttribute("totalPages", pageCount);
		model.addAttribute("page", page);
		return "owner/homemakeList";
	}

	@RequestMapping("/homemakedetail")
	public String ownerdetail(Homemake homemake, int id, Model model,
			HttpSession session) {
		User user = (User) session.getAttribute("user");
		homemake = homemakeBiz.getbyId(id);
		model.addAttribute("detail", homemake);
		return "owner/homemakedetail";
	}

	@RequestMapping("/reportdetail")
	public String addComplaint(Model model, Integer id) {
		id = id == null ? 1 : id;
	
		Owner owner=ownerBiz.getOwner(id);


		model.addAttribute("detail", owner);
		return "owner/reportdetail";
	}

	@RequestMapping(value = "/doreportdetail", method = RequestMethod.POST)
	public String doaddComplaint(Model model, Integer communityId, Integer id,
			String content) {
		//User user=(User) session.getAttribute("user");
		
		Complaint complaint = new Complaint();
		Community community = new Community();
		community.setId(communityId);
		complaint.setCommunity(community);
		Owner owner = new Owner();
		complaint.setType("投诉");
		complaint.setContent(content);
		owner.setId(id);
		complaint.setOwner(owner);

		complaintBiz.addComplaint(complaint);
		return "redirect:handle";
	}

	@RequestMapping("/comdetail")
	public String Complaint(Model model, Integer id) {
		id = id == null ? 1 : id;
		Owner owner=ownerBiz.getOwner(id);
		model.addAttribute("detail", owner);
		return "owner/comdetail";
	}

	@RequestMapping(value = "/docomdetail", method = RequestMethod.POST)
	public String doComplaint(Model model, Complaint complaint, int id,
			int communityId, HttpSession session) throws IllegalStateException,
			IOException {

		String paString = session.getServletContext().getContextPath()
				+ "\\statics\\images\\";
		
		String sqlPath = null;
		// 定义文件保存的本地路径
		String loca="E:\\SS\\property\\src\\main\\webapp\\statics\\images\\";
		
		String localPath = session.getServletContext().getRealPath(
				"statics\\images\\");
		System.out.println(localPath);
		// 定义 文件名

		String filename = null;
		if (!complaint.getFile().isEmpty()) {
			// 生成uuid作为文件名称
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");

			// 获得文件类型（可以判断如果不是图片，禁止上传）
			String contentType = complaint.getFile().getContentType();

			// 获得文件后缀名
			String suffixName = contentType
					.substring(contentType.indexOf("/") + 1);

			// 得到 文件名
			filename = uuid + "." + suffixName;
			// 文件保存路径
			complaint.getFile().transferTo(
					new File(localPath + "\\" + filename));
			
			complaint.getFile().transferTo(
					new File(loca + "\\" + filename));

		}
		// 把图片的相对路径保存至数据库

		sqlPath = "/images/" + filename;

		Complaint complaint1=new Complaint();
		Community community=new Community();
		community.setId(communityId);
		complaint1.setCommunity(community);
		Owner owner =new Owner();
		complaint1.setType("报修");
		complaint1.setContent(complaint.getContent());
		owner.setId(id);

		complaint1.setOwner(owner);
	
		
		complaint1.setRepairsImage(sqlPath);
		complaintBiz.addComplaint(complaint1);
		return "redirect:handle";
	}

	@RequestMapping("/emergency")
	public String Emergency(Model model, Integer id) {
		id = id == null ? 1 : id;
		Management management = managementBiz.getManById(id);
		Community community = communityBiz.getById(id);
		model.addAttribute("management", management);
		model.addAttribute("community", community);
		return "owner/emergency";
	}

	@RequestMapping("/checkinform")
	public String checkinform(HttpSession session, Integer page, Model model) {
		User users = (User) session.getAttribute("user");
		page = page == null ? 1 : page;
		int pageSize = 2;
		int startIndex = (page - 1) * pageSize;
		List<InformTarget> lisTargets = informTargetBiz.getInTarget(
				users.getId(), startIndex, pageSize);
		int row = informTargetBiz.getRowCount(users.getId());
	System.out.println(row);
		int pageCount = (int) Math.ceil((double) row / pageSize);// 页数
		model.addAttribute("lisTargets", lisTargets);
		model.addAttribute("page", page);
		model.addAttribute("totalPages", pageCount);
		return "owner/checkinform";
	}

	@RequestMapping("/informdetail")
	public String informdetail(Model model, InformTarget informTarget, int id) {
		informTarget = informTargetBiz.getById(id);
		informTargetBiz.update(informTarget);
		model.addAttribute("itlist", informTarget);

		return "owner/informdetail";
	}

	@RequestMapping("/ownerhouselist")
	public String ownerhouselist(HttpSession session, Model model) {
		User users = (User) session.getAttribute("user");
		List<Owner> ownerhouesList = ownerBiz.getownerhouseList(users.getId());
		System.out.println(ownerhouesList.size());
		model.addAttribute("ohlist", ownerhouesList);

		return "owner/ownerhouselist";
	}

	@RequestMapping("/ownerhousedetail")
	public String ownerhosuedetail(HttpSession session, Model model, int id) {

		Owner owner = ownerBiz.getownerhousedateil(id);
		Management phoneManagement = managementBiz.ManGetCid(owner
				.getCommunity().getId());
		Community community = communityBiz
				.getById(owner.getCommunity().getId());
		ProvCityDist dist = provCityDistBiz.distAll(community
				.getProvCityDistId());
		ProvCityDist city = provCityDistBiz.cityAll(dist.getCity_id());
		ProvCityDist prov = provCityDistBiz.provAll(city.getProvince_id());
		model.addAttribute("owners", owner);
		model.addAttribute("dist", dist);
		model.addAttribute("city", city);
		model.addAttribute("prov", prov);
		model.addAttribute("phone", phoneManagement);
		return "owner/ownerhousedetail";

	}
	
	@RequestMapping("/handle")
	public String handle(HttpSession session,HttpServletRequest request,Integer page){
		page=page==null?1:page;
		User user = (User) session.getAttribute("user");
		//Owner owner=ownerBiz.getbyId(user.getId());
		int index=(page-1)*3;
		int sum= complaintBiz.getByOid(user.getId(),0,999).size()+1;
		System.out.println(sum);
		List<ComplaintDispose> cdList=complaintBiz.getByOid(user.getId(),index,2);
		request.setAttribute("cdList", cdList);
		request.setAttribute("page", page);
		request.setAttribute("sum", (int)((sum+1)/3));
		return "owner/handle";
	}
	@RequestMapping("/addowner")
	public String addowner(Model model,HttpSession session){
		
		User users=(User) session.getAttribute("user");
		List<Community> list=communityBiz.getList();
		model.addAttribute("list",list);
		model.addAttribute("users",users);
		return "owner/addowner";
		
	}
	
	@RequestMapping("/doaddOwner")
	public String doaddOwner(int id,String name,String phone,String tower1,String tower2,String INhouse,int communityId){
		Owner owner =new Owner();
		System.out.println("**"+id);
		User user=new User();
		user.setId(id);
		owner.setUser(user);
		owner.setName(name);
		owner.setPhone(phone);
		owner.setStatus("未认证");
		String tower=tower1+"栋"+tower2;
		owner.setTower(tower);
		String houseIN = INhouse+"号楼";
		owner.setHouseIN(houseIN);
		Community community =new Community();
		community.setId(communityId);
		owner.setCommunity(community);
		ownerBiz.addOwnerhouse(owner);
		return  "redirect:ownerhouselist";
		
	}

	@RequestMapping(value="/getHandle", method = RequestMethod.POST)
	@ResponseBody
	public ComplaintDispose getHandle(int id){
		ComplaintDispose complaintDispose=complaintBiz.getByCdid(id);
		return complaintDispose;
	}
	
	@RequestMapping("/delinform")
	public String delinform(int id){
		informTargetBiz.delinformTarget(id);
		return "redirect:checkinform";
		
	}
	@RequestMapping("/getTow")
	@ResponseBody
	public int Tow(int id,String tower,String houseIN){
		System.out.println(id+"|"+tower+"|"+houseIN);
		int i = ownerBiz.getOwn(id,tower,houseIN);
		System.out.println(i);
		return i;
	}
}
